$.namespace("warehouse.detail");

warehouse.detail.$form = null;
warehouse.detail.goodsComboboxValueList = null;
warehouse.detail.g$warehouseDetailGrid = null;

/**
 * 画面初始化处理
 */
warehouse.detail.init = function() {
	warehouse.detail.$form = $('#warehouseUpdateForm');
	warehouse.detail.g$warehouseDetailGrid = $("#warehouseDetailGrid");
	
	$.when($.ajax({
		type : 'post',
		url : $.ctx + '/order/goodsList',
		success : function(result) {
			 if (result.isSuccess && result.rslt_flag == "0") {
				 goodsComboboxValueList = result.data;
			 }
		}
	})).done(function(){warehouse.detail.initForm();}).fail(function(){ alert("商品入库画面初始化处理出错啦！"); });
};

/**
 * 
 */
warehouse.detail.initForm = function() {
	var addToolbar = [
		{
			text: '添加', iconCls: 'icon-add', handler: function () {
				warehouse.detail.addDetail();
			}
		}, '-', {
			text: '删除', iconCls: 'icon-remove', handler: function () {
				warehouse.detail.delDetail();
			}
		}];
	
	var editColumn = [{
		field : 'warehouseDetailId',
		hidden : true
	},{
		field : 'goodId',
		title : "商品名称",
		width : 300,
		halign : 'center',
		align : 'left',
		formatter:function(value,row){
            return row.goodName;
        },
        editor:{
            type:'combobox',
            options:{
            	valueField:'goodId',
                textField:'goodName',
                groupField:'typeName',
                data: goodsComboboxValueList,
                required:true
            }
        }
	},{
		field : 'price',
		title : "商品单价",
		width : 80,
		halign : 'center',
		align : 'right',
		editor:{type:'numberbox',options:{required:true, precision:1}}
	},{
		field : 'quantity',
		title : "购买数量",
		width : 80,
		halign : 'center',
		align : 'right',
		editor:{type:'numberbox',options:{required:true, precision:1}}
	},{
		field : 'totalPrice',
		title : "总价",
		width : 80,
		halign : 'center',
		align : 'right',
		formatter:function(value,row) {
			if (row.price == null || row.quantity == null) {
				return 0;
			} else {
				return row.price * row.quantity;
			}
        }
	}];
	
	// 新增
	warehouse.detail.g$warehouseDetailGrid.datagrid({
		rownumbers : true, // 如果为true，则显示一个行号列。
		title:'&nbsp;&nbsp;商品详细信息',
		iconCls: 'icon-edit',
		fitColumns : true, // 真正的自动展开/收缩列的大小，以适应网格的宽度，防止水平滚动
		striped : true,
		height:   222,
		columns : [editColumn],
		toolbar: addToolbar,
		onClickCell: onClickCell,
		onEndEdit: onEndEdit
	});

	// 更新的场合
	if($("#mode").val() == 1) {
		var warehouseId = $("#warehouse_id").val();
		$.ajax({
			type : 'post',
			url : $.ctx + "/warehouse/getEditWarehouseInfoData/" + warehouseId,
			success : function(result) {
				 if (result.isSuccess && result.rslt_flag == "0") {
					 $("#warehouse_name_d").textbox().textbox("setValue", result.data.warehouseName);
					 $("#total_price").textbox().textbox("setValue", result.data.totalPrice);
					 $("#total_price_jp").textbox().textbox("setValue", result.data.totalPriceJp);
					 $("#total_cnt").textbox().textbox("setValue", result.data.totalCnt);
					 $("#freight").textbox().textbox("setValue", result.data.freight);
					 $("#address_id").val(result.data.addressId);
					 $("#user_name").textbox().textbox("setValue", result.data.userName);
					 $("#tel_phone").textbox().textbox("setValue", result.data.telPhone);
					 $("#post_code").textbox().textbox("setValue", result.data.postCode);
					 $("#address").textbox().textbox("setValue", result.data.address);
					 warehouse.detail.g$warehouseDetailGrid.datagrid('loadData',result.data.item);
				 } else {
					 $.messager.alert("提示", "加载订单数据报错！");
				 }
			},
			error:function(result) {
				 $.messager.alert("提示", result);
			}
		});
	}
};

/**
 * 关闭窗口
 */
warehouse.detail.close = function(){
	$('#warehouseEditWin').window('close');
};

/***
 * 保存操作
 */
warehouse.detail.save = function() {
	var allRows = warehouse.detail.g$warehouseDetailGrid.datagrid("getRows");
	if(allRows.length <= 0) {
		$.messager.alert("提示", "请添加商品详细信息！");
		return;
	}
	
	if(!$('#warehouseUpdateForm').form('validate')){
		return false;
	}

	var paramwarehouseDetailArray = [];
	var index = 1;
	var quantity = 0;
	$.each(allRows, function(index, res){
		// 编辑状态END
		warehouse.detail.g$warehouseDetailGrid.datagrid('endEdit', index);
		var info = {
				warehouseDetailId	: res.warehouseDetailId,
				goodId				: res.goodId,
				quantity			: res.quantity,
				price				: res.price,
				totalPrice			: res.totalPrice,
				sort				: index++
		};
		paramwarehouseDetailArray.push(info);
		quantity += parseInt(res.quantity);
	});
	 $("#total_cnt").textbox().textbox("setValue", quantity);
	
	$.messager.confirm("确认", "您确定要更新入库信息吗？", function(ok) {
		if(ok) {
			$('#saveButton').attr('disabled',"disabled");
			$.messager.progress({
				title : "提示",
				text : "数据保存中，请等待...",
			});
			
			$.ajax({
				type : 'POST',
		        url : $.ctx + "/warehouse/saveOrUpdate",
		        data : {
		        	warehouseId					: $("#warehouse_id").val(),
		        	warehouseName				: $("#warehouse_name_d").textbox('getValue'),
					totalPrice					: $("#total_price").textbox('getValue'),
					totalPriceJp				: $("#total_price_jp").textbox('getValue'),
					total_cnt					: $("#total_cnt").textbox('getValue'),
					addressId					: $("#address_id").val(),
					userName					: $("#user_name").textbox('getValue'),
					telPhone					: $("#tel_phone").textbox('getValue'),
					postCode					: $("#post_code").textbox('getValue'),
					address						: $("#address").textbox('getValue'),
					warehouseDetailJsonObject	: JSON.stringify(paramwarehouseDetailArray)
		        },
		        success : function(result) {
		        	$.messager.progress('close');
		        	$('#saveButton').removeAttr('disabled');
		            if (result.isSuccess && result.rslt_flag == "0") {
		            	$.messager.alert("提示", "保存成功");
		            	warehouse.main.g$mainGrid.datagrid('reload');
		            	$('#warehouseEditWin').window('close');
		            } else if(result.rslt_flag == "-1"){
		            	$.messager.alert(common.msg.type.info, '保存失败!');
		            	$.messager.progress('close');
		            }
		        },
		        error: function(error) {
		        	$.messager.progress('close');
		        	$('#saveButton').removeAttr('disabled');
		        }
		    });
		}
	});
}

/**
 * 地址选择画面
 */
warehouse.detail.choose = function () {
	var url = $.ctx + '/warehouse/showAddress?address_id=' + $.trim($("#address_id").val());
	liandisys.dialog.showWindowByItem({
		item : warehouse.main.w$addressWin,
		href : url,
		width : 800,
		height : 'auto',
		resizable : false,
		title : "选择地址信息",
		onLoad: function () {
			warehouse.address.f$backFn = warehouse.detail.f$backFn;
		}
	});
}

/**
 * 地址设定
 */
warehouse.detail.f$backFn = function(row) {
	$("#address_id").val(row[0].addressId);
	$("#user_name").textbox().textbox("setValue", row[0].userName);
	$("#tel_phone").textbox().textbox("setValue", row[0].telPhone);
	$("#post_code").textbox().textbox("setValue", row[0].postCode);
	$("#address").textbox().textbox("setValue", row[0].address);
}


var editIndex = undefined;
function endEditing(){
    if (editIndex == undefined){return true}
    if (warehouse.detail.g$warehouseDetailGrid.datagrid('validateRow', editIndex)){
    	warehouse.detail.g$warehouseDetailGrid.datagrid('endEdit', editIndex);
        editIndex = undefined;
        return true;
    } else {
        return false;
    }
}

function onClickCell(index, field){
    if (editIndex != index){
        if (endEditing()){
        	warehouse.detail.g$warehouseDetailGrid.datagrid('selectRow', index).datagrid('beginEdit', index);
            var ed = warehouse.detail.g$warehouseDetailGrid.datagrid('getEditor', {index:index,field:field});
            if (ed){
                ($(ed.target).data('textbox') ? $(ed.target).textbox('textbox') : $(ed.target)).focus();
            }
            editIndex = index;
        } else {
            setTimeout(function(){
            	warehouse.detail.g$warehouseDetailGrid.datagrid('selectRow', editIndex);
            },0);
        }
    }
}

function onEndEdit(index, row){
    var ed = $(this).datagrid('getEditor', {
        index: index,
        field: 'goodId'
    });
    row.goodName = $(ed.target).combobox('getText');
}

/**
 * 增加行
 */
warehouse.detail.addDetail = function() {
	if (endEditing()){
		warehouse.detail.g$warehouseDetailGrid.datagrid('appendRow',{});
     	editIndex = warehouse.detail.g$warehouseDetailGrid.datagrid('getRows').length - 1;
     	warehouse.detail.g$warehouseDetailGrid.datagrid('selectRow', editIndex).datagrid('beginEdit', editIndex);
	}
}

/**
 * 删除行
 */
warehouse.detail.delDetail = function() {
    if (editIndex == undefined){return}
    warehouse.detail.g$warehouseDetailGrid.datagrid('cancelEdit', editIndex).datagrid('deleteRow', editIndex);
    editIndex = undefined;
}